package leetcode.DFS_BFS;

/**
 * @author mazouri
 * @create 2021-09-23 0:12
 */
public class _436_islandPerimeter {
    int[][] grid;
    int[] dX = {0, 1, 0, -1};
    int[] dY = {1, 0, -1, 0};

    public int islandPerimeter(int[][] grid) {
        this.grid = grid;

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    return dfs(i, j);
                }
            }
        }
        return 0;
    }

    private int dfs(int x, int y) {
        if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) return 1;
        if (grid[x][y] == 0) return 1;
        if (grid[x][y] == 2) return 0;

        grid[x][y] = 2;
        int ans = 0;
        for (int i = 0; i < 4; i++) {
            ans += dfs(x + dX[i], y + dY[i]);
        }
        return ans;
    }
}
